import { defineStore } from 'pinia'
import { ref } from 'vue';
import { routerList } from '@/mock/router';
import { constantRoutes } from '@/router/index';
import { api } from "@/mock/mockApi"
import Layout from '@/layout/index.vue'
import useInfoStore from './use'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.{vue,jsx}');


const usePermissionStore = defineStore('permission', () => {
    // 渲染菜单的路由集合
    const sidebarRouters = ref([...constantRoutes]);

    // 向后端获取路由
    const generateRoutes = () => {
        return new Promise(resolve => {
            api(routerList, 100).then(res => {
                const routeList = addNameToRoutesName(res.data);
                const filterRouter = filterAsyncRouterPermission(routeList);      // 过滤出了只具备权限条件的路由(未组件化)
                const drouter = constantRoutes.concat(filterRouter); // 合并静态路由和动态路由(未组件化)      
                sidebarRouters.value = handleFilterRouter(drouter);
                const sroute = JSON.parse(JSON.stringify(filterRouter)); // 深拷贝路由,不污染数据
                const rewriteRoutes = filterAsyncRouter(sroute); // 动态路由(组件化:添加至路由内置信息中)
                resolve([...rewriteRoutes, {
                    path: "/:pathMatch(.*)*",
                    name: "notFound", // 必须要
                    redirect: '/404',
                    hidden: true,
                }]);
            })
        })
    }

    // 如果你没有写路由的name,那么我就给你补充一个
    const addNameToRoutesName = (routes) => {
        return routes.filter(route => {
            if (route.path === "/" && !route.name) {
                const childNames = route.children.map(child => child.name);

                if (childNames.length === 1) {
                    route.name = childNames[0]; // 设置 name 为子级的 name
                } else {
                    route.name = childNames.map(name => name.charAt(0).toUpperCase()).join(''); // 拼接首字母
                }
            }
            return true;
        });
    }

    //  过滤掉不具备权限的路由(权限过滤)
    const filterAsyncRouterPermission = (asyncRouterMap) => {
        // 过滤掉不需要显示的路由
        const { useInfo } = useInfoStore();
        return asyncRouterMap.reduce((acc, route) => {
            // 过滤子级
            if (route.children && route.children.length > 0) {
                const filteredChildren = filterAsyncRouterPermission(route.children, useInfo.roles);
                // 如果子级有匹配到的内容，保留父级
                if (filteredChildren.length > 0) {
                    acc.push({
                        ...route,
                        children: filteredChildren,
                    });
                }
            } else {
                // 子级为空，直接检查父级
                if (useInfo.roles.includes(route.name)) {
                    acc.push(route);
                }
            }
            return acc;
        }, []);
    }

    //  重构渲染路由的信息结构(控制显示隐藏以及进行渲染的数据格式化)
    const handleFilterRouter = (routerMap) => {
        // 控制显示隐藏
        const hiddenList = routerMap.filter(item => {
            if (!item.hidden) {
                return item;
            }
        })
        // 抹平结构
        const transformedArray = [];
        hiddenList.forEach(item => {
            // 检查 item 的 path 是否有值
            if (item.path && item.path !== '/') {
                transformedArray.push(item);
            } else {
                // 检查 children 是否存在
                if (item.children) {
                    item.children.forEach(child => {
                        transformedArray.push(child);
                    });
                }
            }
        })
        return transformedArray;
    }

    // 编辑后台传递过来的路由字符串,转化为组件对象
    const filterAsyncRouter = (asyncRouterMap) => {
        return asyncRouterMap.filter(route => {
            if (route.component) {
                if (route.component === 'Layout') {
                    route.component = Layout
                } else {
                    route.component = loadView(route.component)
                }
            }
            if (route.children != null && route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children)
            }
            return true;
        })
    }

    const loadView = (view) => {
        let res;
        for (const path in modules) {
            const dir = path.replace(/^\/src\/views\/(.*)\.(vue|jsx|tsx)$/, '\$1');
            if (dir === view) {
                res = () => modules[path]();
            }
        }
        return res;
    }

    return {
        sidebarRouters,
        generateRoutes,
        loadView
    }
})

export default usePermissionStore;